package com.chinda.common.security.handler;

import com.chinda.common.config.jwt.JWTAutoConfiguration;
import com.chinda.common.enums.MessageEnum;
import com.chinda.common.security.SysUserDetails;
import com.chinda.common.utils.JWTTokenUtil;
import com.chinda.common.utils.R;
import com.chinda.common.utils.ResponseUtil;
import com.chinda.common.utils.SecurityUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功处理类
 *
 * @author Wang Chinda
 * @date 2020/7/11
 * @see
 * @since 1.0
 */
@Slf4j
@Component
@AllArgsConstructor
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    private final JWTAutoConfiguration jwtAutoConfiguration;

    /**
     * 登录成功返回
     * @param request
     * @param response
     * @param authentication
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        SysUserDetails userDetails =  (SysUserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();
        // 组装JWT
        SysUserDetails userDetail = SecurityUtil.getUserDetail();
        String accessToken = JWTTokenUtil.createAccessToken(userDetail);
        accessToken = jwtAutoConfiguration.getTokenPrefix() + accessToken;
        log.info(MessageEnum.SYS_SECURITY_0001.getMsg(username) + "\taccessToken: " + accessToken);
        ResponseUtil.outJson(response, R.ok(MessageEnum.SYS_SECURITY_0001.getMsg(username)).put("accessToken", accessToken).put("expiration", jwtAutoConfiguration.getExpiration()));
    }
}
